package com.master.config;

import com.master.domain.MiaoshaUser;
import com.master.service.MiaoshaUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginRequredInterceptor implements HandlerInterceptor {

    @Autowired
    HostHolder hostHolder;

    @Autowired
    MiaoshaUserService miaoshaUserService;

    //在所有请求之前做拦截
    //判断用户身份
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String token = null;
        if(httpServletRequest.getCookies() != null){
            for(Cookie cookie : httpServletRequest.getCookies()){
                if(cookie.getName().equals(MiaoshaUserService.COOK1_NAME_TOKEN)){
                    //找到对应的Cookie之后,取出Cookie的值,然后根据token从redis中取出MiaoshaUser信息
                    token = cookie.getValue();
                    break;
                }
            }
        }
        if(token != null) {
            //从redis中获取用户信息
            //并且重置Cookie有效期,相当于活跃了一次session
            MiaoshaUser user = miaoshaUserService.getByToken(token, httpServletResponse);
            if (user == null) {
                return true;
            }
            hostHolder.setUser(user);
            return true;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        hostHolder.clear();
    }
}
